/**
 * 敏感词检查系统 Mock 数据
 */

// 模拟敏感词数据
const mockKeywords = [
  { id: 1, word: '傻逼', category: '不文明词语', description: '不文明用词', createdAt: '2024-01-01 10:00:00' },
  { id: 2, word: '操你妈', category: '不文明词语', description: '不文明用词', createdAt: '2024-01-01 10:01:00' },
  { id: 3, word: '法轮功', category: '政治敏感', description: '政治敏感词', createdAt: '2024-01-01 10:02:00' },
  { id: 4, word: '赌博', category: '违法违规', description: '违法活动', createdAt: '2024-01-01 10:03:00' },
  { id: 5, word: '色情', category: '违法违规', description: '违法内容', createdAt: '2024-01-01 10:04:00' },
  { id: 6, word: '商业机密', category: '商业敏感', description: '商业敏感信息', createdAt: '2024-01-01 10:05:00' },
  { id: 7, word: '种族歧视', category: '歧视言论', description: '歧视性言论', createdAt: '2024-01-01 10:06:00' },
  { id: 8, word: '网络霸凌', category: '网络暴力', description: '网络暴力行为', createdAt: '2024-01-01 10:07:00' },
]

// 模拟数据库配置
const mockDatabases = [
  {
    id: 'db1',
    name: '主业务数据库',
    host: 'localhost',
    port: 3306,
    database: 'main_business',
    type: 'mysql',
    status: 'connected',
    tables: ['users', 'posts', 'comments', 'articles', 'user_profiles', 'orders', 'products']
  },
  {
    id: 'db2', 
    name: '用户数据库',
    host: 'localhost',
    port: 3306,
    database: 'user_system',
    type: 'mysql',
    status: 'connected',
    tables: ['user_info', 'user_settings', 'user_logs', 'user_feedback']
  },
  {
    id: 'db3',
    name: '内容管理数据库',
    host: 'localhost',
    port: 3306,
    database: 'cms_system',
    type: 'mysql', 
    status: 'connected',
    tables: ['cms_articles', 'cms_categories', 'cms_tags', 'cms_comments']
  }
]

// 模拟检查结果
const generateMockResults = (keywords, tables) => {
  const results = []
  
  // 检查参数有效性
  if (!keywords || keywords.length === 0) {
    console.warn('⚠️ 敏感词列表为空，无法生成结果')
    return results
  }
  
  if (!tables || tables.length === 0) {
    console.warn('⚠️ 表列表为空，无法生成结果')
    return results
  }
  
  const sampleContents = [
    '这个产品真是傻逼设计，完全不好用',
    '用户评论：这个功能真的很垃圾，操你妈的',
    '文章内容包含了一些法轮功相关的敏感信息',
    '论坛帖子讨论赌博网站的推广方式',
    '用户上传的图片包含色情内容',
    '内部文档泄露了商业机密信息',
    '评论区出现了种族歧视的言论',
    '用户举报遭受网络霸凌行为',
    '这种傻逼操作真的让人无语',
    '又是法轮功的宣传内容'
  ]
  
  // 生成随机结果
  for (let i = 0; i < 50; i++) {
    const keyword = keywords[Math.floor(Math.random() * keywords.length)]
    const table = tables[Math.floor(Math.random() * tables.length)]
    const content = sampleContents[Math.floor(Math.random() * sampleContents.length)]
    const recordId = Math.floor(Math.random() * 10000) + 1
    
    results.push({
      id: i + 1,
      tableName: table,
      columnName: ['content', 'title', 'description', 'comment', 'text'][Math.floor(Math.random() * 5)],
      recordId: recordId,
      keyword: keyword.word,
      category: keyword.category,
      context: content,
      fullContent: content + '...(更多内容)',
      sqlQuery: `SELECT * FROM ${table} WHERE id = ${recordId};`,
      createdAt: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString(),
      status: 'pending'
    })
  }
  
  return results
}

// 模拟任务数据
let mockTasks = []
let taskIdCounter = 1

// 模拟API延迟
const delay = (ms = 1000) => new Promise(resolve => setTimeout(resolve, ms))

// Mock API 函数
export const mockSensitiveWordAPI = {
  // 敏感词管理
  async getKeywords() {
    await delay(500)
    return {
      success: true,
      data: mockKeywords,
      total: mockKeywords.length
    }
  },

  async addKeyword(keyword) {
    await delay(300)
    const newKeyword = {
      id: Math.max(...mockKeywords.map(k => k.id)) + 1,
      ...keyword,
      createdAt: new Date().toISOString()
    }
    mockKeywords.push(newKeyword)
    return {
      success: true,
      data: newKeyword
    }
  },

  async updateKeyword(id, keyword) {
    await delay(300)
    const index = mockKeywords.findIndex(k => k.id === parseInt(id))
    if (index !== -1) {
      mockKeywords[index] = { ...mockKeywords[index], ...keyword, updatedAt: new Date().toISOString() }
      return {
        success: true,
        data: mockKeywords[index]
      }
    }
    throw new Error('敏感词不存在')
  },

  async deleteKeyword(id) {
    await delay(300)
    const index = mockKeywords.findIndex(k => k.id === parseInt(id))
    if (index !== -1) {
      mockKeywords.splice(index, 1)
      return { success: true }
    }
    throw new Error('敏感词不存在')
  },

  async batchImport(file) {
    await delay(1000)
    // 模拟解析文件并导入
    const importedCount = Math.floor(Math.random() * 20) + 5
    return {
      success: true,
      data: {
        imported: importedCount,
        skipped: 2,
        errors: 0
      }
    }
  },

  // 数据库管理
  async getDatabases() {
    await delay(300)
    return {
      success: true,
      data: mockDatabases
    }
  },

  async getTables(databaseId) {
    await delay(500)
    const database = mockDatabases.find(db => db.id === databaseId)
    if (database) {
      return {
        success: true,
        data: database.tables
      }
    }
    throw new Error('数据库不存在')
  },

  async testConnection(config) {
    await delay(2000)
    return {
      success: true,
      data: { connected: true, message: '连接成功' }
    }
  },

  // 检查任务管理
  async startCheck(config) {
    await delay(500)
    const taskId = `task_${taskIdCounter++}`
    const task = {
      taskId,
      status: 'running',
      config,
      createdAt: new Date().toISOString(),
      progress: {
        percentage: 0,
        message: '准备开始检查...',
        checkedTables: 0,
        totalTables: config.tables?.length || mockDatabases.find(db => db.id === config.databaseId)?.tables.length || 10,
        foundIssues: 0,
        elapsedTime: 0
      }
    }
    
    mockTasks.push(task)
    
    // 模拟进度更新
    setTimeout(() => {
      this.simulateProgress(taskId)
    }, 1000)
    
    return {
      success: true,
      data: task
    }
  },

  async getProgress(taskId) {
    await delay(200)
    const task = mockTasks.find(t => t.taskId === taskId)
    if (task) {
      return {
        success: true,
        data: task.progress
      }
    }
    throw new Error('任务不存在')
  },

  async getResults(taskId) {
    await delay(500)
    const task = mockTasks.find(t => t.taskId === taskId)
    if (task && task.status === 'completed') {
      const database = mockDatabases.find(db => db.id === task.config.databaseId)
      const results = generateMockResults(mockKeywords, database?.tables || [])
      // console.log('🔍 生成的检查结果:', {
        taskId,
        keywordsCount: mockKeywords.length,
        tablesCount: database?.tables?.length || 0,
        resultsCount: results.length
      })
      return {
        success: true,
        data: results
      }
    }
    // console.log('⚠️ 任务未完成或不存在:', { taskId, task: task?.status })
    return {
      success: true,
      data: []
    }
  },

  async stopCheck(taskId) {
    await delay(300)
    const task = mockTasks.find(t => t.taskId === taskId)
    if (task) {
      task.status = 'stopped'
      task.progress.message = '检查已停止'
      return { success: true }
    }
    throw new Error('任务不存在')
  },

  async getTasks(params = {}) {
    await delay(300)
    return {
      success: true,
      data: mockTasks,
      total: mockTasks.length
    }
  },

  // 模拟进度更新
  simulateProgress(taskId) {
    const task = mockTasks.find(t => t.taskId === taskId)
    if (!task || task.status !== 'running') return
    
    const startTime = Date.now()
    
    const updateProgress = () => {
      if (task.status !== 'running') return
      
      const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000)
      const progress = Math.min(100, elapsedSeconds * 10) // 每秒增加10%，10秒完成
      
      task.progress = {
        ...task.progress,
        percentage: progress,
        message: progress < 100 
          ? `正在检查表 ${Math.min(Math.floor(progress / 10) + 1, task.progress.totalTables)}/${task.progress.totalTables}...`
          : '检查完成',
        checkedTables: Math.min(Math.floor(progress / 10), task.progress.totalTables),
        foundIssues: Math.floor(Math.random() * progress / 2),
        elapsedTime: elapsedSeconds
      }
      
      if (progress >= 100) {
        // 完成检查
        task.status = 'completed'
        task.progress.percentage = 100
        task.progress.status = 'completed'  // 重要：添加这一行
        task.progress.message = '检查完成'
        task.completedAt = new Date().toISOString()
      } else {
        setTimeout(updateProgress, 1000)
      }
    }
    
    updateProgress()
  }
}

// 安装 Mock 拦截器
export const setupMockAPI = () => {
  // 这里可以使用 MSW 或其他 Mock 库
  // 或者直接在 API 文件中判断环境使用 Mock 数据
  
  if (process.env.NODE_ENV === 'development') {
    // console.log('🔧 敏感词检查系统 Mock API 已启用')
    
    // 可以在这里设置 axios 拦截器或其他 Mock 方案
    // 暂时返回 Mock 对象供直接调用
    return mockSensitiveWordAPI
  }
  
  return null
}
